<template>
  <HModal ref="HModal" class="relation-selector-modal"
          @ok="handleOK" @cancel="close" :visible="visible"
          :width="width" :height="height" title="关联列表">
    <RelationSelectorModalLayout :key="manual.id">
      <RelationSelectorSearch :loading="loading" ref="search" @search="search" :formDefinition="formDefinition"
                              :manual="manual" slot="header" />
      <RelationSelectorTable :currentSelectedRow.sync="currentSelectedRow" :multiple="multiple"
                             :data-source="dataSource" :loading="loading" @selected="handleOK"
                             ref="table" :formDefinition="formDefinition"
                             :manual="manual" />
      <RelationSelectorTableFooter :loading="loading" @pageChange="simpleSearch" :pagination="pagination"
                                   slot="footer" />
    </RelationSelectorModalLayout>
  </HModal>
</template>
<script>
import HModal from '@comp/hhd/HModal/HModal.vue'
import RelationSelectorModalLayout
  from '@comp/hhd/design/FormEngine/RelationWrapper/RelationSelectorModal/RelationSelectorModalLayout.vue'
import RelationSelectorSearch
  from '@comp/hhd/design/FormEngine/RelationWrapper/RelationSelectorModal/search/RelationSelectorSearch.vue'
import { createManual, createRelation } from '@comp/hhd/design/relation/types'
import { getAction, postAction } from '@api/manage'
import { createFormDefinition, readFormDefinitionVo } from '@comp/hhd/design/FormDesigner/types'
import RelationSelectorTable
  from '@comp/hhd/design/FormEngine/RelationWrapper/RelationSelectorModal/table/RelationSelectorTable.vue'
import RelationSelectorTableFooter
  from '@comp/hhd/design/FormEngine/RelationWrapper/RelationSelectorModal/footer/RelationSelectorTableFooter.vue'
import { createPagination, createProps } from '@/utils'

export default {
  name: 'RelationSelectorModal',
  components: {
    RelationSelectorTableFooter,
    RelationSelectorTable,
    RelationSelectorSearch,
    RelationSelectorModalLayout,
    HModal
  },
  props: {
    context: createProps(Object, () => undefined),
    formModel: createProps(Object, () => undefined),
    rowIndex: createProps(Number),
    rowId: createProps(String),
    multiple: createProps(Boolean, false),
    subFormId: createProps(String) //如果当前是一个明细表表头上的引用, 那么subFormId不为空
  },
  data() {
    return {
      currentSelectedRow: undefined,
      width: 1000,
      height: 500,
      visible: false,
      loading: false,
      pagination: createPagination(20),
      relation: createRelation(),
      manual: createManual(),
      dataSource: [],
      formDefinition: createFormDefinition()
    }
  },
  methods: {
    setData({ relation, manual }) {
      this.prepare(relation, manual)
      this.open()
      this.$nextTick(() => {
        this.$refs.HModal.top = -50
      })
    },
    handleOK() {
      if (!this.multiple) {
        //单选的功能
        if (!this.currentSelectedRow) return this.$message.warn('请选择关联数据')
        this.manualRelation(this.currentSelectedRow)
      } else {
        //多选的功能
        let rows = this.getSelectionRows()
        if (!rows || !rows.length) return this.$message.warn('请选择关联数据')
        this.manualRelations(rows)
      }
    },
    getSelectionRows() {
      return this.$refs.table.getSelectionRows()
    },
    manualRelations(relationDataArray) {
      this.loading = true
      postAction('/form/manualRelationArray', {
        relationDataArray,
        sourceFormDefinitionId: this.relation.relationSourceFormId,
        targetFormDefinitionId: this.relation.relationTargetFormId,
        relationId: this.relation.id,
        manualId: this.manual.id,
        formModel: this.formModel,
        rowId: this.rowId,
        actionId: this.context.actionId,
        subFormId: this.subFormId,
      }).then(data => {
        if (data.success) {
          let { formModel } = data.result
          this.changeFormModel(formModel)
          this.close()
        } else {
          this.$notification.error({message: data.message, duration: 3})
        }
        this.loading = false
      }).catch(error => {
        console.log(error)
        this.loading = false
        this.$notification.error({message: error, duration: 3})
      })
    },
    manualRelation(relationData) {
      this.loading = true
      postAction('/form/manualRelationById', {
        relationData,
        sourceFormDefinitionId: this.relation.relationSourceFormId,
        targetFormDefinitionId: this.relation.relationTargetFormId,
        relationId: this.relation.id,
        manualId: this.manual.id,
        formModel: this.formModel,
        rowId: this.rowId,
        actionId: this.context.actionId
      }).then(data => {
        if (data.success) {
          let { formModel } = data.result
          this.changeFormModel(formModel)
          this.close()
        } else {
          this.$notification.error({ message: data.message, duration: 3 })
        }
        this.loading = false
      }).catch(error => {
        console.log(error)
        this.loading = false
        this.$notification.error({ message: error, duration: 3 })
      })
    },
    changeFormModel(formModel) {
      if (this.context && this.context.changeFormModel) {
        this.context.changeFormModel(formModel)
      }
    },
    simpleSearch() {
      let params = this.$refs.search.getParams()
      this.search(params, false)
    },
    search(params, resetPage = true) {
      this.$refs.table.clearSelection()
      params.pageNo = this.pagination.current
      params.pageSize = this.pagination.pageSize
      params.manualId = this.manual.id
      params.relationId = this.relation.id
      params.sourceFormId = this.context.formDefinition.id
      params.formModel = this.formModel
      params.rowId = this.rowId
      params.rowIndex = this.rowIndex
      resetPage && (params.pageNo = this.pagination.current = 1)
      this.doSearch(params)
    },
    doSearch(params) {
      this.loading = true
      postAction('/form/queryManualRelationData', params).then(data => {
        if (data.success) {
          this.dataSource = data.result.records
          this.pagination.total = data.result.total
          this.pagination.current = data.result.current
        } else {
          this.$notification.error({ message: data.message, duration: 3 })
        }
        this.loading = false
      }).catch(error => {
        console.log(error)
        this.loading = false
        this.$notification.error({ message: error, duration: 3 })
      })
    },
    open() {
      this.visible = true
    },
    prepare(relation, manual) {
      this.width = window.innerWidth - 100
      this.height = window.innerHeight - 100
      this.relation = relation
      this.manual = manual
      this.currentSelectedRow = undefined
      this.loadFormDefinition()
    },
    readFormDefinition(formDefinitionVo) {
      this.formDefinition = readFormDefinitionVo(formDefinitionVo)
      this.$nextTick(() => {
        this.$refs.search.search()
      })
    },
    loadFormDefinition() {
      this.loading = true
      getAction('/form/queryById', { id: this.relation.relationTargetFormId }).then(data => {
        if (data.success) {
          this.readFormDefinition(data.result)
        } else {
          this.$notification.error({ message: data.message, duration: 3 })
        }
        this.loading = false
      }).catch(error => {
        console.log(error)
        this.loading = false
        this.$notification.error({ message: error, duration: 3 })
      })
    },
    close() {
      this.visible = false
    }
  }
}
</script>
<style>
.relation-selector-modal .ant-modal-body {
  padding: 0;
}
</style>